package com.homevip.util.http;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

/**
 * http协议工具类
 * 
 * @author mojs
 * 
 */
public class HttpUtil {

	/**
	 * 获取经常代理后的真实ip
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			if (null != ip && ip.equals("0:0:0:0:0:0:0:1%0")) ip = "127.0.0.1"; // localhost
		}
		if(ip.indexOf(",") > -1){
			ip = ip.split(",")[0];
		}
		return ip;
	}

	/**
	 * encodeURL中的中文
	 */
	public static String encodeUrl(String url) throws Exception {
		if (url.indexOf("/") != -1) {
			url = url.replace("\\", "/");
			String path = url.substring(0, url.lastIndexOf("/"));
			String filename = url.substring(url.lastIndexOf("/") + 1,
					url.length());
			filename = java.net.URLEncoder.encode(filename, "utf-8");
			filename = filename.replace("+", "%20");
			return path + "/" + filename;
		} else {
			return url;
		}
	}

	/**
	 * 接收request流
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static String getRequestAsString(HttpServletRequest request)
			throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];
		int read;
		InputStream in = request.getInputStream();
		do {
			read = in.read(buf);
			if (read > 0)
				out.write(buf, 0, read);
		} while (read > 0);
		String ret = out.toString("utf-8");
		out.close();
		out = null;
		return ret;
	}
	
	public static String getHeader(HttpServletRequest request){
		String ua = request.getHeader("User-Agent");
		return ua;
	}
}
